
const util = require("./util/util");
const dbUtil = require("./util/dbUtil");
const apiUtil = require("./util/apiUtil");

exports.main = async (context) => {
    return { ...context };
};


exports.saveDataToDB = async (context) => {
    const data = context.data;
    const cloud = context.cloud;
    // const res = await cloud.db.createCollection('userInfo');
    // cloud.db.insertMany([])

    if (!data.userInfo.name) return { code: 404, msg: 'name 为必传值哦！' }

    let findResult = await cloud.db.collection("userInfo").find({
        name: data.userInfo.name
    })

    if (findResult.length > 0) {
        let res = await cloud.db.collection("userInfo").updateMany({ name: data.userInfo.name }, { $set: { avater: data.userInfo.avater } })
        return { res, code: 200, msg: "修改成功" }
    }

    // if (Object.prototype.toString.call(data.userInfo) == '[object Array]') {
    //     let res = await cloud.db.collection("userInfo").insertMany(data.userInfo)
    //     return { res, code: 200, msg: "数据保存成功" }
    // }
    let res = await cloud.db.collection("userInfo").insertMany([{ ...data.userInfo }]);
    return { res, code: 200, msg: "数据保存成功" }
}

exports.removeDataToDB = async (context) => {
    const data = context.data;
    const cloud = context.cloud;

    let findResult = await cloud.db.collection("userInfo").find({
        name: data.userInfo.name
    })

    if (findResult.length > 0) {
        let res = await cloud.db.collection("userInfo").deleteMany({ name: data.userInfo.name })
        return { res, code: 200, msg: "删除成功" }
    }
    return { findResult, code: 200, msg: '数据为空' }
}

exports.findDataToDB = async (context) => {
    const data = context.data;
    const cloud = context.cloud;

    let findResult = await cloud.db.collection("userInfo").find({
        name: data.userInfo.name
    })

    return { findResult, code: 200, msg: "查找出全部数据" }
}

exports.randomNumber = async (context) => {
    const { max, min } = context.data;
    const prizeIndex = await util.getRandom(min, max);
    let test = await new Promise((res, rej) => {
        setTimeout(() => {
            res(prizeIndex)
        }); 
    }) 

    return { prizeIndex: test }

}



